<template>
  <view class="manager-item-box">
    <ve-card
      :title="managerItem.licenseNo || '-'"
      :sub-title="managerItem.operateStatusName"
      :type="getStatus(managerItem.operateStatus)"
      @click="onDetailClick"
    >
      <!-- <ve-cell label="车牌号">{{ managerItem.licenseNo || '-' }}</ve-cell> -->
      <!-- <ve-cell label="状态">{{ managerItem.operateStatusName }}</ve-cell> -->
      <!-- <ve-cell label="车架号">{{ managerItem.vin }}</ve-cell> -->
      <ve-cell label="归属门店">{{ managerItem.siteName }}</ve-cell>
      <ve-cell label="当前里程">{{ managerItem.totalMileage || '-' }} 公里</ve-cell>
      <ve-cell label="下次保养里程">
        <span class="mr-24">{{ managerItem.estimatedKilometre || '-' }} 公里</span>
        <span :style="{ color: getMileageStatus(managerItem).color }">{{ getMileageStatus(managerItem).text }}</span>
      </ve-cell>
      <ve-cell label="交强险到期日">
        <span  class="mr-24">{{ managerItem.compulsoryEndDate || '-' }}</span>
        <span :style="{ color: getFormattedDateDiff(managerItem.compulsoryEndDate).color }">{{ getFormattedDateDiff(managerItem.compulsoryEndDate).text }}</span>
      </ve-cell>
      <ve-cell label="商业险到期日">
        <span  class="mr-24">{{ managerItem.businessEndDate || '-' }}</span>
        <span :style="{ color: getFormattedDateDiff(managerItem.businessEndDate).color }">{{ getFormattedDateDiff(managerItem.businessEndDate).text }}</span>
      </ve-cell>
      <ve-cell label="年检有效期至">
        <span  class="mr-24">{{ managerItem.planTime || '-' }}</span>
        <span :style="{ color: getFormattedDateDiff(managerItem.planTime).color }">{{ getFormattedDateDiff(managerItem.planTime).text }}</span>
      </ve-cell>
      <ve-operate-list :operates="operates" :record="managerItem" />
    </ve-card>

    <!-- TODO:晓强把处置车辆和更换车牌号放到了list页面，注释掉 -->
    <!-- 处置车辆 -->
    <!-- <DisposePlate v-model:visible="plate.disposeVisible" :id="plate.id" @confirm="onConfirmDispose" /> -->

    <!-- 更换车牌号 -->
    <!-- <ReplicePlate v-model:visible="plate.repliceVisible" :id="plate.id" :plateNumber="managerItem.licenseNo" @confirm="onConfirmReplice" /> -->

    <ve-modal title="确认删除？" v-model="visible" @confirm="onConfirm" @close="onClose" :okLoading="okLoading">
      <div class="font-medium">
        删除车辆将会连带删除此车辆关联的运维单以及运维单的财务数据和待办数据，车辆相关的订单和订单的财务数据仍保留，但会导致被删车辆订单的部分操作无法进行。如需保留此车辆关联的全部数据，请使用车辆【处置】功能
      </div>
      <view class="checkbox-box">
        <ve-checkbox-group @change="onChange">
          <ve-checkbox :key="1" v-model="isRead" name="我已阅读并知晓风险"> 我已阅读并知晓风险 </ve-checkbox>
        </ve-checkbox-group>
      </view>
    </ve-modal>
  </view>
</template>
<script setup lang="ts">
  import { getStatus } from '../models'
  // import DisposePlate from './dispose-plate.vue'
  // import ReplicePlate from './replice-plate.vue'
  import { deleteCar } from '@/api/asset/car-manager'
  import { userStore } from '@/stores'
  import { isValid } from '@/utils'
  import dayjs from 'dayjs'
  import { ref } from 'vue'

  const props = defineProps({
    managerItem: {
      type: Object,
      default: () => ({}),
    },
    resetRefresh: {
      type: Function,
      default: () => {},
    },
    from: {
      type: String,
      default: '',
    },
  })

  const visible = ref(false)
  const userInfoStore = userStore()
  const { role } = userInfoStore.profile
  const rowRecord = ref<any>({})
  const isRead = ref(false)
  // 回显剩余 或 已超 的公里数
  const getMileageStatus = (record: any) => {
    if (!isValid(record.estimatedKilometre)) {
      return ''
    }
    let totalMileage = record.totalMileage ? record.totalMileage : 0
    const mileageDiff = record.estimatedKilometre - totalMileage // 计算差距

    if (mileageDiff >= 0) {
      return {
        text: `剩余 ${mileageDiff} 公里`, // 剩余公里数
        color: '#00b42a', // 绿色
      }
    } else if (mileageDiff < 0) {
      return {
        text: `已超 ${Math.abs(mileageDiff)} 公里`, // 已超公里数
        color: '#f76965', // 红色
      }
    } else {
      return '-'
    }
  }
  const getFormattedDateDiff = (newValue: any) => {
    if (!newValue) {
      return '-'
    }
    const today = dayjs().startOf('day') // 获取当前日期，忽略时分秒
    const endDate = dayjs(newValue).startOf('day') // 转换到期日期，忽略时分秒
    const diffDays = endDate.diff(today, 'day') // 计算天数差
    if (diffDays >= 0) {
      return {
        text: `剩余 ${diffDays} 天`, // 剩余天数
        color: '#00b42a', // 绿色
      }
    } else {
      return {
        text: `已超 ${Math.abs(diffDays)} 天`, // 已超天数
        color: '#f76965', // 红色
      }
    }
  }

  // operateStatus: 40 处置
  const operates = ref([
    {
      label: '详情',
      permission: 'svmsapp:car-manage.detail',
      method: (record: any) => {
        onDetailClick()
      },
    },
    {
      label: '车辆库存',
      permission: 'svmsapp:car-manage.stock',
      show: (record) => record.operateStatus !== 40,
      method: (record: any) => {
        const data_josn = JSON.stringify({
          modelId: record.modelId,
          modelName: record.modelName,
          carId: record.id,
          licenseNo: record.licenseNo,
          siteId: record.siteId,
        })
        uni.navigateTo({
          url: `/pages/asset/stock/car-stock/car?data_json=` + data_josn,
        })
      },
    },
    {
      label: '归还',
      permission: 'svmsapp:car-manage.return',
      show: (record: any) => record.source == 2,
      method: (record: any) => {
        uni.navigateTo({ url: `/pages/asset/car-manager/return-car?carId=${record.id}` })
      },
    },
    {
      label: '费用信息',
      permission: 'svmsapp:car-manage.fee',
      // show: (record) => record.status !== '已处置',
      method: (record: any) => {
        console.log(record)
        uni.navigateTo({
          url: `/pages/asset/car-manager/fee-info?id=${record.id}`,
        })
      },
    },
    {
      label: '编辑',
      permission: 'svmsapp:car-manage.edit',
      show: (record: any) => record.operateStatus !== 40,
      method: (record: any) => {
        uni.navigateTo({
          url: `/pages/asset/car-manager/form/index?id=${record.id}`,
        })
      },
    },
    {
      label: '更换车牌号',
      permission: 'svmsapp:car-manage.change-license-no',
      show: (record) => record.operateStatus !== 40,
      method: (record: any) => {
        console.log(record)
        // plate.repliceVisible = true
        uni.$emit('repliceVisibleFn', props.managerItem)
      },
    },
    {
      label: '添加费用',
      permission: 'svmsapp:car-manage.add-fee',
      show: (record) => record.source !== 2,
      method: (record: any) => {
        console.log(record)
        uni.navigateTo({
          url: `/pages/asset/car-manager/add-fee?carId=${record.id}&operateType=0`,
        })
      },
    },
    {
      label: '处置',
      permission: 'svmsapp:car-manage.dispose',
      //【租赁中】【已处置】【借调（借入）】，不支持处置操作
      show: (record) => record.operateStatus != 10 && record.operateStatus != 40 && record.source != 2,
      method: (record: any) => {
        console.log(record)
        // plate.disposeVisible = true
        uni.$emit('disposeVisibleFn', props.managerItem)
      },
    },
    {
      label: '更换车型',
      permission: 'svmsapp:car-manage.changemodel',
      show: (record) => record.operateStatus !== 40,
      method: (record: any) => {
        console.log(record)
        uni.navigateTo({
          url: `/pages/asset/car-manager/change-model?record=${JSON.stringify(record)}`,
        })
      },
    },
    {
      label: '新增维修',
      permission: 'svmsapp:car-manage.add-repair',
      method: (record: any) => {
        uni.navigateTo({
          url: `/pages/asset/car-repair/form/index?pageType=create&licenseNo=${record.licenseNo}&origin=carManagerList&carId=${record.id}`,
        })
      },
    },
    {
      label: '新增保养',
      permission: 'svmsapp:car-manage.add-maintenance',
      method: (record: any) => {
        uni.navigateTo({
          url: `/pages/asset/car-maintenance/form?carId=${record.id}&from=carManagerList`,
        })
      },
    },
    {
      label: '删除',
      // permission: 'svmsapp:car-manage.delete',
      show: (record) => role.some((item: any) => item.adminRole === 1),
      method: (record: any) => {
        console.log(record)
        visible.value = true
        rowRecord.value = record
      },
    },
    {
      label: '新增商业险',
      permission: 'svmsapp:car-manage.add-insurance',
      method: (record: any) => {
        uni.navigateTo({
          url: `/pages/asset/car-insure/form?insureKind=1&carId=${record.id}&from=carManagerList`,
        })
      },
    },
    {
      label: '新增交强险',
      permission: 'svmsapp:car-manage.add-insurance',
      method: (record: any) => {
        uni.navigateTo({
          url: `/pages/asset/car-insure/form?insureKind=0&carId=${record.id}&from=carManagerList`,
        })
      },
    },
    {
      label: '新增年检',
      permission: 'svmsapp:car-manage.add-inspect',
      method: (record: any) => {
        uni.navigateTo({
          url: `/pages/asset/car-inspect/form?carId=${record.id}&from=carManagerList`,
        })
      },
    },
  ])

  // const plate = reactive({
  //   repliceVisible: false,
  //   disposeVisible: false,
  //   id: props.managerItem.id,
  // })

  const onDetailClick = () => {
    const permissions = userInfoStore.permissons
    if (permissions.includes('svmsapp:car-manage.detail')) {
      uni.navigateTo({ url: `/pages/asset/car-manager/detail/index?id=${props.managerItem.id}&from=${props.from}` })
    }
  }

  // const onConfirmDispose = (form: any) => {
  //   disposeCar(form)
  //     .then(() => {
  //       console.log('处置车辆成功')
  //       plate.disposeVisible = false
  //     })
  //     .catch((error) => {
  //       uni.showToast({
  //         title: error.data.message,
  //         icon: 'none',
  //         mask: true,
  //       })
  //     })
  // }

  // const onConfirmReplice = (form: any) => {
  //   changeLicenseNo(form).then(() => {
  //     plate.repliceVisible = false
  //     props.resetRefresh()
  //   })
  // }

  const okLoading = ref(false)
  const onConfirm = () => {
    if (isRead.value) {
      okLoading.value = true
      deleteCar({ id: rowRecord.value.id })
        .then(() => {
          visible.value = false
          props.resetRefresh()
        })
        .finally(() => {
          setTimeout(() => {
            okLoading.value = false
          }, 500)
        })
    } else {
      uni.showToast({
        title: '请阅读上述风险并完成勾选',
        icon: 'none',
        mask: true,
      })
    }
  }

  const onClose = () => {
    okLoading.value = false
    isRead.value = false
  }

  const onChange = (option: any) => {
    console.log('option', option)
    if (option.length > 0) {
      isRead.value = option[0].checked
    } else {
      isRead.value = false
    }
  }
</script>
<style scoped lang="less">
  .font-medium {
    font-weight: 500;
  }
  .checkbox-box {
    display: flex;
    justify-content: flex-end;
    padding: 32rpx 0;
  }
  .manager-item-box {
    .card-footer {
      width: 100%;
      height: 100%;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-between;
      padding: 32rpx 0;

      .operate-list {
        width: 100%;
        font-size: 28rpx;
        font-weight: 400;
        color: #8491a8;
      }

      .ve-button {
        margin-left: 24rpx;
        margin-bottom: 24rpx;
      }
    }
  }
  .mr-24 {
    margin-right: 24rpx;
  }
</style>
